package com.example.goodpet.activity;

import static com.amap.api.services.core.ServiceSettings.updatePrivacyAgree;
import static com.amap.api.services.core.ServiceSettings.updatePrivacyShow;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentTransaction;

import com.amap.api.maps2d.MapsInitializer;
import com.example.goodpet.R;
import com.example.goodpet.base.BaseFragment;
import com.example.goodpet.chat.fragment.ChatFragment1;
import com.example.goodpet.community.bean.UserTieziInfo;
import com.example.goodpet.community.fragment.CommunityContent;
import com.example.goodpet.community.fragment.CommunityFragment;
import com.example.goodpet.db.DatabaseHelper;
import com.example.goodpet.home.fragment.HomeFragment;
import com.example.goodpet.my.MyFragment;
import com.example.goodpet.release.fragment.ReleaseFragment;
import com.example.goodpet.utils.ActivityManager;
import com.example.goodpet.utils.MyApplication;
import com.example.goodpet.utils.UIUtils;
import com.hyphenate.chat.EMClient;
import com.zackratos.ultimatebarx.ultimatebarx.java.UltimateBarX;

import java.util.ArrayList;


public class MainActivity extends FragmentActivity {
    //final
    private String TAG=this.getClass().getSimpleName();
    public final int LOGIN_REQ_CHAT=100;
    public final int LOGIN_REQ_MY=101;
    public final int LOGIN_REQ_COMMUNITY=102;
    public final int TIEZIINFO=110;
    private FrameLayout frameLayout;
    private RadioGroup rgMain;
    RadioButton home;
    RadioButton community;
    RadioButton release;
    RadioButton chat;
    RadioButton my;
    private ArrayList<BaseFragment> fragments;
    //fragment所在的位置
    private int position = 0;
    //缓存的fragment / 上次显示的fragment
    private BaseFragment tempFragment;
    private RadioButton rbHomeLocation;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        UltimateBarX.statusBarOnly(this)
                .fitWindow(true)
                .colorRes(R.color.ic_back_background)
                .light(true)
                .apply();


        ActivityManager.getInstance().addActivity(this);

        frameLayout=findViewById(R.id.frameLayout);
        rgMain=findViewById(R.id.rg_main);
        home=findViewById(R.id.rb_home);
        community=findViewById(R.id.rb_community);
        release=findViewById(R.id.rb_release);
        chat=findViewById(R.id.rb_chat);
        my=findViewById(R.id.rb_my);

        updatePrivacyShow(this,true,true);
        updatePrivacyAgree(this,true);

        //初始化Fragment
        initFragment();
        //设置RadioGroup的监听
        initListener();
        //初始化数据库
        DatabaseHelper.getInstance(this).initDb();
    }

    private void initListener() {
        rgMain.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId){
                    case R.id.rb_home:
                        position = 0;
                        break;
                    case R.id.rb_community:
                        if (MyApplication.user==null){
                            switchRadio(position).setChecked(true);
                            community.setChecked(false);
                            startActivityForResult(new Intent(MainActivity.this,LoginActivity.class),LOGIN_REQ_COMMUNITY);
                        }else {
                            position = 1;
                        }
                        break;
                    case R.id.rb_release:
                        //position = 2;
                            release.setChecked(false);
                            switchRadio(position).setChecked(true);
                            ReleaseFragment releaseFragment = new ReleaseFragment();
                            releaseFragment.show(getSupportFragmentManager(),"dialog");
                        break;
                    case R.id.rb_chat:
                        if (MyApplication.user==null){
                            switchRadio(position).setChecked(true);
                            chat.setChecked(false);
                            startActivityForResult(new Intent(MainActivity.this,LoginActivity.class),LOGIN_REQ_CHAT);
                        }else {
                            position = 2;
                        }

                        break;
                    case R.id.rb_my:
                        if (MyApplication.user==null) {
                            switchRadio(position).setChecked(true);
                            my.setChecked(false);
                            startActivityForResult(new Intent(MainActivity.this,LoginActivity.class),LOGIN_REQ_MY);
                        } else {
                            position = 3;
                        }
                        //position = 3;
                        break;
                    default:
                        position = 0;
                        break;
                }
                BaseFragment baseFragment = getFragment(position);

                /**
                 * 第一参数：上次显示的fragment
                 * 第二参数：当前正要显示的fragment
                 */
                switchFragment(tempFragment,baseFragment);
            }
        });
        rgMain.check(R.id.rb_home);

    }

    public void initFragment(){
        fragments=new ArrayList<>();
        fragments.add(new HomeFragment());
        fragments.add(new CommunityFragment());
        //fragments.add(new ReleaseFragment());
        fragments.add(new ChatFragment1());
        fragments.add(new MyFragment());
    }

    private BaseFragment getFragment(int position){
        if (fragments != null && fragments.size() > 0) {
            BaseFragment baseFragment = fragments.get(position);
            return baseFragment;
        }
        return null;
    }

    /**
     * 切换fragment
     * @param fromFragment
     * @param nextFragment
     */
    private void switchFragment(Fragment fromFragment,BaseFragment nextFragment){
        if(tempFragment != nextFragment){
            tempFragment = nextFragment;
            if(nextFragment != null){
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                //判断nextFragment是否添加
                if(!nextFragment.isAdded()){
                    //隐藏当前fragment
                    if(fromFragment != null){
                        transaction.hide(fromFragment);
                    }
                    transaction.add(R.id.frameLayout,nextFragment).commit();
                }else{
                    //隐藏当前fragment
                    if(fromFragment!=null){
                        transaction.hide(fromFragment);
                    }
                    transaction.show(nextFragment).commit();
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==RESULT_OK)
            if (requestCode==LOGIN_REQ_CHAT){
                switchRadio(position).setChecked(false);
                chat.setChecked(true);
                position=2;
                switchFragment(tempFragment,getFragment(position));
            }else if (requestCode==LOGIN_REQ_MY){
                switchRadio(position).setChecked(false);
                my.setChecked(true);
                position=3;
                switchFragment(tempFragment,getFragment(position));
            }else if(requestCode==LOGIN_REQ_COMMUNITY){
                switchRadio(position).setChecked(false);
                my.setChecked(true);
                position=1;
                switchFragment(tempFragment,getFragment(position));
            }else if(requestCode==TIEZIINFO){
                UserTieziInfo info = data.getParcelableExtra("info");
                int position = data.getIntExtra("position", -1);
                if(position!=-1 && null!=info){
                    ((CommunityFragment) fragments.get(1)).refresh(position,info);
                }
            }
    }
    public void toActivity(Class<? extends Activity> clazz){
        startActivity(new Intent(UIUtils.getContext(),clazz));
    }

    /**
     * 返回当前处在那个radioButton
     * @param position
     * @return
     */
    private RadioButton switchRadio(int position){
        switch (position){
            case 0:return home;
            case 1:return community;
            case 2:return chat;
            case 3:return my;
        }
        return null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EMClient.getInstance().chatManager().removeMessageListener(MyApplication.msgListener);
        EMClient.getInstance().logout(true);
        DatabaseHelper.getInstance(this).closeDb();
    }

}